<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2018/1/16
  Time: 16:58
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>添加销售计划</title>
    <jsp:include page="../headPage.jsp"></jsp:include>
</head>
<body>
<input type="hidden" id="entryPerson" name="entryPerson">
<div id="addModelTable_outDiv" style="height: 80%;width: 100%">


    <%--<div id="toolbar" class="btn-group">
        <button id="btn_add" type="button" class="btn btn-default">
            <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增产品
        </button>
        <button id="btn_delete" type="button" class="btn btn-default">
            <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除产品
        </button>
    </div>--%>

</div>

<!--          客户选择表单       -->
<div class="modal fade" id="customerModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog" style="width: 60%;height: 50%">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                <h4 class="modal-title" id="customerModalLabel">修改客户信息</h4>
            </div>

            <input id="customerId" hidden="hidden">
            <table id="td_customerTable"></table>

            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="backCus()" id="backCus">确定</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div>

<!--          客户选择表单       -->
<div class="modal fade" id="proListModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog" style="width: 60%;height: 50%">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                <h4 class="modal-title" id="proListModalLabel">新增订单</h4>
            </div>

            <table id="td_proListTable"></table>

            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="backPro()" id="backPro">确定</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div>
</body>
<%String j=request.getParameter("id"); %>
<script>


	function toastrStyle(){
		toastr.options = {
            "closeButton": false,
            "debug": false,
            "newestOnTop": false,
            "progressBar": false,
            "positionClass": "toast-top-center",
            "preventDuplicates": false,
            "onclick": null,
            "showDuration": "5000",
            "hideDuration": "1000",
            "timeOut&quot": "100000",
            "extendedTimeOut": "0",
            "showEasing": "swing",
            "hideEasing": "linear",
            "showMethod": "fadeIn",
            "hideMethod": "fadeOut"
        }; 
	}
	
    //页面加载时执行
    $(function (){
        var orderId = <%= j%>;
        //更具ID查询  出库单
        comAjax("${pageContext.request.contextPath }/yzl/findReturnById.do",{id:orderId},function(data){
            //将得到的customerID 写入到影藏的input中
            $("#customerId").val(data.customerId);
            $("#entryPerson").val(data.entryPerson);
            console.log("data?????????????",data);
            initAddTable(data.returnsNumber,data.returnsDate,data.entryPersonName,data.customerName,""/* ,"销售经理或副总经理或总经理" */,orderId);
        })
    })


    //返回list页面
    function backList(){
        window.location.href = "${pageContext.request.contextPath }/pages/yzlERP/return/salesReturns.jsp";
    }
    
    function setAmount(data,price,productStock,outQ){
    	var id=data.id.slice(9);
    	var num=data.value*price;
    	var maxNum = productStock>outQ?outQ:productStock;
    	if(data.value>maxNum){
    		toastrStyle();
    		toastr.warning('退货数量不能大于出库数量或库存');
    		$('#'+data.id).val(maxNum);
    		$('#amount'+id).val(maxNum*price);
    	}
    	var reg=/^[1-9]\d*$|^0$/;
    	if(!reg.test(data.value)){
    		toastrStyle();
    		toastr.warning('只能输入正整数');
    		var num=data.value.split('.')[0];
    		$('#'+data.id).val(num);
    		$('#amount'+id).val(num*price);
    	}else{
    		$('#amount'+id).val(data.value*price);
    	}
    }

    //关闭当前页面
    function closeNow(){
        var tab = parent.tab;
        tab.deleteTab(tab.getCurrentTabId());
    }

    //修改
    function updateReturn(){
    	var entryPerson = $('#entryPerson').val();
    	var addTime = $('#addTime').val();
        if (addTime=='') {
        	toastrStyle();
        	toastr.warning('请输入日期');
        	return false;
        }
        var d1=new Date(addTime);
        var nowDate = new Date();
        var d2 = new Date(nowDate.getFullYear() + "-" + (nowDate.getMonth() + 1) + "-" + nowDate.getDate());
        if(d1<d2){
        	toastrStyle();
        	toastr.warning('退货日期不能小于当前日期');
        	return false;
        }
        //得到选择的客户ID
        var customerId = $("#customerId").val();
        //得到原来的表格数据
        var allTableData = $('#td_addModelTable').bootstrapTable('getData');//获取表格的所有内容行
        //循环将填写的数量填入表格
        for(var i=0;i<allTableData.length;i++){
            var count = $("#addTIndex"+allTableData[i].id).val();
            var reason = $("#returnReason"+allTableData[i].id).val();
            console.log(reason)
            allTableData[i].planQ = count;
            allTableData[i][0] = undefined;
            if(reason==''){
            	toastrStyle();
            	toastr.warning('请填写退货理由！');
            	return false;
            }else{
            	allTableData[i].returnReason = reason;
            }
        }
        //得到选择的客户ID
        var customerId = $("#customerId").val();
        var obj = dedaoValue("td_addModelTable");
        var obj1 = {
            id : <%= j%>,
            number : obj.number,
            customerId : customerId,
            planDate : obj.time,
            productors : allTableData,
            entryPerson : entryPerson
        };
        $("#update").attr("disabled",true);
        $.ajax({
            url : "${pageContext.request.contextPath }/yzl/updateReturnFrom.do",
            type : "POST",
            data : JSON.stringify(obj1),
            contentType: "application/json; charset=utf-8",
            dataType : "json",
            success : function(data){
                if(data == 1){
                	toastrStyle();
                	toastr.success("修改成功！");
                    setTimeout(function(){  //使用  setTimeout（）方法设定定时3000毫秒
						//关闭模态框
						// 父页面刷新
                		backList();
					},2000);
                    //关闭当前窗口
                    //closeNow();
                    //$("#btn_save").attr("data-dismiss","modal");
                }else{
                	toastrStyle();
                    toastr.warning("修改失败！");
                }
            }
        })
    }

    function addPro(){initProductorsTable()}

    //选择客户
    function choseCustomer(){initCustomerTable()}

    //选择客户 返回带回数据 关闭第二层模态框 第一层模态框表格重新加载
    function backCus(){

        //得到修改的ID
        var orderId = $("#updateOrderNumId").val();
        //得到选择的数据
        var rows = $('#td_customerTable').bootstrapTable('getSelections')[0];
        //得到原来的表头信息
        var objTable = dedaoValue("td_addModelTable");
        if(rows){
            //关闭第二层模态框
            $("#backCus").attr("data-dismiss","modal");
            //更新第一层模态框的表格
            initAddTable(objTable.number,objTable.time,rows.name,rows.name,"1111"/* ,rows.name */,<%= j%>);
            //给customerId赋值
            $("#customerId").val(rows.id);
        }else{
        	toastrStyle();
            toastr.warning("请选择客户");
        }
    }

    //选择产品
    function backPro(){
        //得到选择的数据
        var rows = $('#td_proListTable').bootstrapTable('getSelections');
        //得到原来的表格数据
        var allTableData = $('#td_addModelTable').bootstrapTable('getData');//获取表格的所有内容行
        for(var j=0;j<rows.length;j++){
            allTableData.push(rows[j]);
        }
        //得到原来的表头信息
        var objTable = dedaoValue("td_addModelTable");
        if(rows){
            //关闭模态框
            $("#proListModal").modal('hide');
            //更新第一层模态框的表格
            initAddTable(objTable.number,objTable.time,rows.name,objTable.customer,"1111"/* ,rows.name */);

            for(var i=0;i<allTableData.length;i++){
                //for(var x = 0;x<rows.length;x++){
                //if(rows[x].id != allTableData[i].id){
                $('#td_addModelTable').bootstrapTable('insertRow', {
                    index:$('#td_addModelTable').bootstrapTable('getOptions').totalRows,
                    row:allTableData[i]
                });
                //}
                //}
            }
        }else{
        	toastrStyle();
            toastr.warning("请选择客户");
        }
    }

    //统一请求ajax
    function comAjax(url,data,fuc){
        $.ajax({
            type:"POST",
            url:url,
            data:data,
            success:function (data) {
                fuc(data);
            },
        })
    }
</script>


<script>

    //初始化客户表单
    function initCustomerTable(){
    	$('#td_customerTable').bootstrapTable({
            dataType: "json",
            method: 'get',
            contentType: "application/x-www-form-urlencoded",
            cache: false,
            clickToSelect: true,
            pagination: true,                   //是否显示分页（*）
            queryParams : function (params) {
                //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
                var temp = {
                    limit: params.limit,                         //页面大小
                    offset: (params.offset / params.limit) + 1,   //页码
                };
                return temp;
            },
            singleSelect : true, // 单选checkbox
            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1,                       //初始化加载第一页，默认第一页
            pageSize: 8,                       //每页的记录行数（*）
            pageList: [5,8],        //可供选择的每页的行数（*）
            url: "${pageContext.request.contextPath }/hpf/customerPageList.do",
            columns: [
                [
                    { checkbox: true },
                    {
                        field: 'name',
                        title: "名称",
                        valign: "middle",
                        align: "center"
                    },
                    {
                        field:"phone",
                        title: "手机号",
                        valign: "middle",
                        align: "center"
                    }
                ]
            ]
        });
        $("#customerModal").modal({keyboard: true,})
    }

    //初始化产品表单
    function initProductorsTable(){
        $('#td_proListTable').bootstrapTable({
            dataType: "json",
            method: 'get',
            contentType: "application/x-www-form-urlencoded",
            cache: false,
            clickToSelect: true,    //是否启用点击选中行
            //singleSelect : true, // 单选checkbox
            //: "/pages/yzlERP/data/
            url: "${pageContext.request.contextPath }/yzl/carList.do",
            columns: [
                [
                    { checkbox: true },
                    {
                        field: 'carType',
                        title: "车种",
                        valign: "middle",
                        align: "center"
                    },
                    {
                        field:"nameP",
                        title: "品名",
                        valign: "middle",
                        align: "center"
                    },
                    {
                        field:"numberP",
                        title: "品编",
                        valign: "middle",
                        align: "center"
                    }
                ]
            ]
        });
        $("#proListModal").modal({keyboard: true,})
    }

    //添加表格初始化
    function initAddTable(number,time,entryPerson,customer,beforeNumber/* ,approvedMan */,id,modalId){
        var $addModelTable_outDiv = $("#addModelTable_outDiv");
        if($addModelTable_outDiv.find("table").length > 0){
            $addModelTable_outDiv.empty();
        }
        var table = '<table id="td_addModelTable"></table>'
        $addModelTable_outDiv.append(table);

        var listH = '<div class="modal-footer">\n' +
            '        <button type="button" class="btn btn-default" onclick="backList()">返回列表页面</button>\n' +
            '    </div>'
        $addModelTable_outDiv.append(listH);

        var div = '<div class="modal-footer">\n' +
            //'                    <button type="button" class="btn btn-primary" style="float:left" onclick="addPro()">添加产品</button>\n' +
            //'                    <button type="button" class="btn btn-primary" style="float:left">删除产品</button>\n' +
            //'                    <button type="button" class="btn btn-default" onclick="closeNow()">关闭</button>\n' +
            '                    <button type="button" id="update" class="btn btn-primary" onclick="updateReturn()">保存</button>\n' +
            '                </div>';
        $addModelTable_outDiv.append(div);

        if(time == "" || time == null){
            time = '<input type="text" name="addTime" id="addTime"\n' +
                '                               placeholder="yyyy-mm-dd"\n' +
                '                               class="form_datetime form-control"\n' +
                '                               >'
        }else{
            time = '<input type="text" name="addTime" id="addTime"\n' +
                '                               placeholder='+time+'\n' +
                '                               class="form_datetime form-control"\n' +
                '                               value="'+time+'">'
        }
        if(customer == "" || customer == null){
            customer = '<a href="#" onclick="choseCustomer()">选择客户</a>';
        }else{
            /* customer = '<a href="#" onclick="choseCustomer()">'+customer+'</a>'; */
            customer = customer;
        }

        newurl = "${pageContext.request.contextPath }/yzl/returnXq.do?id="+id;

        $('#td_addModelTable').bootstrapTable({
            dataType: "json",
            method: 'get',
            contentType: "application/x-www-form-urlencoded",
            cache: false,
            toolbar: '#toolbar',
            url : newurl,
            columns: [
                [
                    /* {
                        field : id,
                        valign: 'middle',
                        hidden:true,
                        align: "center",
                    }, */
                    {
                        field: 'name',
                        title: "销售退货单",
                        valign: "middle",
                        align: "center",
                        colspan: 1
                    },
                    {
                        title: number,
                        valign: "middle",
                        align: "center",
                        colspan: 1,
                    },
                    {
                        title: '计划时间',
                        valign: "middle",
                        align: "center",
                        colspan: 2,
                    },
                    {
                        title: time,
                        valign: "middle",
                        align: "center",
                        colspan: 1,
                    },
                    {
                        title: "指定人",
                        valign: "middle",
                        align: "center",
                        colspan: 1,
                    },
                    {
                        title: entryPerson,
                        valign: "middle",
                        align: "center",
                        colspan: 1,
                    }
                ],
                [

                    /* {
                        field : id,
                        valign: 'middle',
                        hidden:true,
                    }, */
                    {
                        field: 'name',
                        title: "客户",
                        valign: "middle",
                        align: "center",
                        colspan: 1
                    },
                    {
                        title: customer,
                        valign: "middle",
                        align: "center",
                        colspan: 6,
                    },
                    /* {
                        title: "审批人",
                        valign: "middle",
                        align: "center",
                        colspan: 1,
                    },
                    {
                        title: approvedMan,
                        valign: "middle",
                        align: "center",
                        colspan: 1,
                    }, */
                ],
                [

                    /* {   field : id,
                        title: '序号',//标题  可不加
                        formatter: function (value, row, index) {
                            return index+1;
                        }
                    }, */
                    {
                        field: 'carType',
                        title: '车种',
                        valign: "middle",
                        align: "center",
                        formatter: function (value, row, index) {
                        	return row.cartype;
                        }
                    },
                    {
                        field: 'numberP',
                        title: '品编',
                        valign: "middle",
                        align: "center",
                        formatter: function (value, row, index) {
                        	return row.num;
                        }
                    },
                    {
                        field: 'nameP',
                        title: '品名',
                        valign: "middle",
                        align: "center",
                        formatter: function (value, row, index) {
                        	return row.name;
                        }
                    },
                    {
                        field: 'outQ',
                        title: '退货数量',
                        valign: "middle",
                        align: "center",
                        formatter: function (value, row, index) {
                        	console.log(row)
							if (row.rLastOutQ > 0) {
                        		if(row.returnQ > 0){
                                    return '<input type="number" min="0" oninput="setAmount(this,'+row.remark8+','+row.productStock+','+(row.returnQ+row.rLastOutQ)+')" class="form-control" id="addTIndex'+row.id+'" value="'+row.returnQ+'">'
                                }else{
                                    return '<input type="number" min="0" oninput="setAmount(this,'+row.remark8+','+row.productStock+','+(row.returnQ+row.rLastOutQ)+')" class="form-control" id="addTIndex'+row.id+'">'
                                }
							} else {
								if(row.returnQ > 0){
	                                return '<input type="number" readonly min="0" class="form-control" id="addTIndex'+row.id+'" value="'+row.returnQ+'">'
	                            }else{
	                                return '<input type="number" readonly min="0" class="form-control" id="addTIndex'+row.id+'">'
	                            }
							}
                        }
                    },
                    {
                        field: 'remark8',
                        title: '单价',
                        valign: "middle",
                        align: "center"
                    },
                    {
                        field: 'amount',
                        title: '金额',
                        valign: "middle",
                        align: "center",
                        formatter: function (value, row, index) {
                        	return '<input type="number" readonly class="form-control" id="amount'+row.id+'" value="'+row.amount+'">'
                        }
                    },
                    {
                        field: 'returnReason',
                        title: '退货理由',
                        valign:"middle",
                        align:"center",
                        formatter: function (value, row, index) {
                        	if(row.returnReason!=null){
                        		return '<input type="type" class="form-control" value="'+row.returnReason+'" id="returnReason'+row.id+'">'
                        	}else{
                        		return '<input type="type" class="form-control" id="returnReason'+row.id+'">'
                        	}
                        }
                    }/* ,
                    {
                        field: 'dayConsumptionQ',
                        title: '日消耗量',
                        valign: "middle",
                        align: "center"
                    } */

                ]
            ]
        });
        $(function () {
    		$(".form_datetime").datetimepicker({
    		 format: "yyyy-mm-dd",
    		 autoclose: true,
    		 todayBtn: true,
    		 todayHighlight: true,
    		 showMeridian: true,
    		 pickerPosition: "bottom-center",
    		 language: 'zh-CN',//中文，需要引用zh-CN.js包
    		 startView: 2,//月视图
    		 minView: 2//日期时间选择器所能够提供的最精确的时间选择视图
    		 });
    	 });

        //$('#'+modalId).modal({keyboard: true,});
        //$("#toolbarIn").css("display","block");

    }

    //根据传入的表格ID 查询数据
    function dedaoValue(tableId){

        //拿到原来表格中填写的订单号和时间
        var $thead  = $($($("#"+tableId)[0]).find("thead")[0]);
        //拿到第一行
        var $tr1 = $($thead.find("tr")[0]);
        //拿到订单号
        var number = $($($tr1.find("th")[1]).find("div")[0]).text();
        //拿到时间
        var time = $("#addTime").val();


        //拿到第二行
        var $tr2 = $($thead.find("tr")[1]);
        //拿到客户名称
        var customer = $($($tr2.find("th")[1]).find("div")[0]).text();
        var obj = {
            number : number,
            time : time,
            customer : customer
        };
        return obj;
    }

</script>

<!-- 时间插件   -->
<script>
    layui.use(['form', 'layedit', 'laydate'], function () {
        var form = layui.form(),
            layer = layui.layer,
            layedit = layui.layedit,
            laydate = layui.laydate;

        //创建一个编辑器
        var editIndex = layedit.build('LAY_demo_editor');
        //自定义验证规则
        form.verify({
            title: function (value) {
                if (value.length < 5) {
                    return '标题至少得5个字符啊';
                }
            },
            pass: [/(.+){6,12}$/, '密码必须6到12位'],
            content: function (value) {
                layedit.sync(editIndex);
            }
        });

        //监听提交
        form.on('submit(demo1)', function (data) {
            layer.alert(JSON.stringify(data.field), {
                title: '最终的提交信息'
            })
            return false;
        });
    });


</script>
</html>
